import Taro from '@tarojs/taro';

const baseUrl = 'http://60.247.158.187:8006'

//网络请求拦截器
const interceptor = function (chain) {
    const requestParams = chain.requestParams;
    const { method, data, url, headers } = requestParams;
    let token = Taro.getStorageSync('TOKEN'); //拿到本地缓存中存的token
    requestParams.header = {
        ...requestParams.header,
        Authorization: 'Bearer ' + token //将token添加到头部
    };
    return chain.proceed(requestParams).then(res => {
        return res;
    });
};

Taro.addInterceptor(interceptor);

const request = async (method, url, params) => {
    // let contentType = 'application/x-www-form-urlencoded';
    // if (params && params.data) contentType = 'application/json';
    // if (params && params.headers && params.headers.contentType) {
    //     contentType = params.headers.contentType;
    // }
    const option = {
        method,
        url: baseUrl + url,
        data: params,
        header: {
            'content-type': 'application/json',
        },
    };

    const resp = await Taro.request(option).then(res => {
        return res.data;
    }).catch(err => {
        console.log('api', '请求接口出现问题', err);
        throw err;
    });

    return resp;
};

export default {
    get: (url, config) => request('GET', url, config),
    post: (url, config) => request('POST', url, config),
    put: (url, config) => request('PUT', url, config),
    delete: (url, config) => request('DELETE', url, config),
    patch: (url, config) => request('PATCH', url, config),
};